package DataStructure.SortMethod;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @time: 2021/4/26/026 14:52
 * @author: Zhurunhe
 */
public class BuBBleSort {
    public static void main(String[] args) {
        int max=100000;
        int[] arr = new int[max];
        for (int i = 0; i < max; i++) {
            arr[i] = (int) (Math.random() * max);
        }
        //测试冒泡排序的速度
        Date date1 = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time1=simpleDateFormat.format(date1);
        System.out.println("排序前的时间为："+time1);



//        for (int i = 0; i < arr.length; i++) {
//
//            System.out.printf(" " + arr[i]);
//        }
        System.out.println();
        bulbblesort(arr);
        System.out.println();
        Date date2 = new Date();
        String time2=simpleDateFormat.format(date2);
        System.out.println("排序后的时间为："+time2);

    }

    public static void bulbblesort(int[] arr) {
        int temp;
        boolean isExchange=false;
        //冒泡排序的时间复杂度O(n^2)
        for (int j = 0; j < arr.length-1; j++) {
            for (int i = 0; i < arr.length - 1-j; i++) {//arr.length - 1 即为需要循环n-1 -j是前面的逆序还需要多少次排序
                if (arr[i]>arr[i + 1]  ) {
                    isExchange=true;
                    temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }
           // System.out.println("第"+(j+1)+"次排序");
            //System.out.println(Arrays.toString(arr));
            if (isExchange){
                isExchange=false;
            }else {
                break;
            }
        }
//        System.out.println("-----------------------------");
//        for (int i = 0; i < arr.length; i++) {
//
//            System.out.printf(" " + arr[i]);
//        }
    }

}
